/*
 * @Descripttion: 
 * @Author: junhuafly
 * @Date: 2020-03-04 10:29:05
 * @LastEditors: junhuafly
 * @Email: junhuafly@163.com
 * @LastEditTime: 2020-04-14 16:39:23
 */
// pages/queryOrder/index.js
const appInst = getApp();

import {
  orderAPI,
  goodsAPI
} from './../../api/index'
import {
  returnStatus,
  returnStatusToast,
  getPromise,
  afterNav,
  payOrder
} from './../../utils/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showPost: false,
    orderId: 2909,
    buyerRemark: '',
    relates: [],
    confirmOrder: false
  },

  // 操作确认订单
  handleConfirmOrder() {
    const status = this.data.orderInfo.orderStatus
    switch (status) {
      case 3:
        this.setData({
          confirmOrder: true
        })
        break;
        // TODO: 付款
      case 1:

        break;
        // 评价
      default:
        wx.navigateTo({
          url: '/pages/mine/order/evaluate/index',
          success: (res) => {
            res.eventChannel.emit('params', {
              info: {
                details: this.data.orders
              }
            })
          }
        });
        break;
    }
  },
  // 关闭弹窗
  handleCancel() {
    this.setData({
      confirmOrder: false
    })
  },
  // 确认弹窗操作
  handleConfirm() {
    orderAPI.confirmGoodsReceive({
      orderId: this.data.orderId
    }).then(res => {
      returnStatusToast(res, () => {
        wx.redirectTo({
          url: '/pages/mine/order/success/index',
          success: (result) => {

          },
          fail: () => {},
          complete: () => {}
        });
      })
    })
  },
  // 取消订单
  cancelOrder() {
    if (this.data.orderInfo.orderStatus === 1) {
      orderAPI.cancelOrder({
        orderId: this.data.orderId
      }).then(res => {
        returnStatusToast(res, () => {
          this.initData()
        })
      })
    } else {
      wx.navigateTo({
        url: `/pages/mine/order/logistics/package/index?orderId=${this.data.orderId}`,
      });
    }
  },
  // 售后
  onAfterSale({
    target: {
      dataset: {
        info,
        info: {
          aftersaleStatus: status
        }
      }
    }
  }) {
    afterNav(info, status)
  },

  initData() {
    // 加载初始化数据
    orderAPI.handleOrder({
      method: 'get',
      orderId: this.data.orderId
    }).then(async res => {
      const o = await returnStatus(res)
      this.setData({
        orderInfo: o,
        addressInfo: {
          receiver: o.receiver,
          phone: o.phone,
          isDefault: o.isDefaultAddress,
          province: o.province,
          city: o.city,
          district: o.district,
          detailAddress: o.detailAddress
        }
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function ({
    orderId,
    type
  }) {
    this.setData({
      orderId: orderId * 1,
      type
    })
    appInst.setTitle(type ? '订单详情' : '订单确认')
    if (type) {
      // 获取推荐信息
      goodsAPI.queryGoodsRelate().then(async res => {
        const relates = await returnStatus(res)
        this.setData({
          relates
        })
      })
    }
    this.params = {
      orderId: this.data.orderId
    }
    this.initData()
    // 加载数据
    let info = ['queryOrderDetail', 'queryOrderShipWay', 'queryOrderCoupon']
    let info_key = ['orders', 'shipInfo', 'couponInfo']
    if (type) {
      info = [info.shift()]
      info_key = [info_key.shift()]
    }
    getPromise.call(this, info, info_key, {
      API: orderAPI,
      params: this.params
    }).then(res => {

    })

  },
  async onChange({
    detail: shipMode
  }) {
    // 修改配送方式
    const res = await orderAPI.putOrderShipMode({
      ...this.params,
      shipMode
    })
    const resShip = this.data.shipInfo.filter(item => {
      return item.shipMode == shipMode
    })[0]
    returnStatusToast(res, () => {
      this.setData({
        'orderInfo.shipMode': shipMode * 1,
        'orderInfo.shipModeName': resShip.shipModeName,
        'orderInfo.postFee': resShip.postFee,
        'orderInfo.payment': this.data.orderInfo.orderPrice - this.data.orderInfo.discount+resShip.postFee,
        showPost: false
      })
    })
  },
  // 确认订单
  async onSubmit() {
    const {orderId} = this.data
    const res = await orderAPI.confirmOrder({
      orderId,
      buyerRemark: this.data.buyerRemark
    })
    const _ = await returnStatus(res)
    if (_ === '确认成功') {
      // 提交订单成功
      // 成功提交订单
      const res = await payOrder(orderId,this.data.orderInfo.orderCode)
    }
  },
  // 选择优惠券
  // 选择优惠券跳转到优惠券页面点击选择优惠券
  chooseCoupon() {
    const _this = this
    wx.navigateTo({
      url: `/pages/mine/coupon/index?customerCouponId=${this.data.orderInfo.discountId}&title=选择优惠券`,
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        getCoupon({
          customerCouponId
        }) {
          orderAPI.chooseCoupon({
            customerCouponId,
            "orderId": _this.data.orderId
          }).then(res => {
            returnStatus(res).then(() => {
                let msg = ''
                let couponInfo = {}
                if (customerCouponId != 0) {
                  _this.data.couponInfo.some(item => {
                    if (item.customerCouponId == customerCouponId) {
                      couponInfo = item
                      return true
                    }
                  })
                  msg = couponInfo.name
                }
                _this.setData({
                  'orderInfo.discountName': msg,
                  'orderInfo.discountId': customerCouponId,
                  'orderInfo.discount': couponInfo.discountValue,
                  'orderInfo.payment': _this.data.orderInfo.orderPrice - couponInfo.discountValue+_this.data.orderInfo.postFee
                })
                console.log(_this.data.orderInfo)
            })
          })
        },
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('params', {
          coupons: _this.data.couponInfo
        })
      }
    })

  },
  // 选择更改地址
  chooseAddress() {
    const _this = this;
    if (![0,1].includes(this.data.orderInfo.orderStatus)) return
    wx.navigateTo({
      url: '/pages/address/index?type=1',
      events: {
        getAddress({
          info: addressInfo
        }) {
          orderAPI.modifyAddress({
            "addressId": addressInfo.addressId,
            "orderId": _this.data.orderId
          }).then(async res => {
            returnStatusToast(res, () => {
              _this.setData({
                addressInfo
              })
            })
          })
        }
      }
    })

  },
  getRemark({
    detail: buyerRemark
  }) {
    this.setData({
      buyerRemark
    })
  },
  // 显示配送方式
  showShip() {
    if (![0,1].includes(this.data.orderInfo.orderStatus)) return
    if (this.data.type) return
    this.setData({
      showPost: true
    })
  },
  closeShip() {
    this.setData({
      showPost: false
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})